<script lang="ts" setup>
import { reactive, ref, onMounted, defineAsyncComponent } from 'vue'
import { queryFaultRequestData, queryFaultTableCol } from '@/api/operation/types/operation'
import { QueryFault, queryFaultMessage, renewFaultStatus, SendMessage } from '@/api/operation'
import { useTable } from '@/hooks/useTable'
import { Action, ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { getToken } from '@/utils/cache/cookies'
import dayjs from 'dayjs'
import { findStoreByName } from '@/api/store'
import { faultStatus } from '@/types/enum'
import { maintenanceShortTermBike } from '@/api/bike'
import { isTimeBikeCode } from '@/utils/validate'
const form = reactive<queryFaultRequestData>({
  status: '',
  workOrderId: '',
  phone: '',
  operator: '',
  storeId: ''
})
const storeName = ref<string[]>([])
const formRef = ref<FormInstance | null>(null)
const { data, loading, pagination, load, handleCurrentChange, handleSizeChange, setCurrentPage } =
  useTable<queryFaultTableCol>(QueryFault, getToken() ?? '', () => form)
const handleFormSearch = () => {
  setCurrentPage(1)

  load()
}
const reset = () => {
  formRef.value?.resetFields()
}
const getStoreName = () => {
  findStoreByName({
    token: getToken() ?? '',
    storeName: ''
  }).then((res) => {
    if (res.statusCode === '0') {
      storeName.value = res.data.map((item) => item.storeName)
    }
  })
}

const formatStatus = (status: faultStatus) => {
  switch (status) {
    case 0:
      return '未处理'
    case 1:
      return '待处理'
    case 2:
      return '处理中'
    case 3:
      return '已处理'
    case 4:
      return '已忽略'
    default:
      break
  }
}
const formatStatusColor = (status: faultStatus) => {
  switch (status) {
    case 0:
      return {
        color: 'var(--xy-warning-color)'
      }
    case 1:
      return {
        color: 'var(--xy-warning-color)'
      }
    case 2:
      return {
        color: 'var(--xy-warning-color)'
      }
    case 3:
      return {
        color: 'var(--xy-success-color)'
      }
    case 4:
      return {
        color: 'var(--xy-grey-text-color)'
      }
    default:
      break
  }
}
onMounted(() => {
  load()
  getStoreName()
})
const handled = (row: queryFaultTableCol) => {
  try {
    ElMessageBox.alert('请确认该条故障上报是否处理完成', '处理完成', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      callback: async (action: Action) => {
        if (action === 'confirm') {
          renewFaultStatus({
            token: getToken() ?? '',
            faultId: row.faultId.toString(),
            status: 3
          })
            .then((res) => {
              if (res.statusCode === '0') {
                ElMessage.success(res.data)
                load()
              }
            })
            .catch((error) => {
              console.error(error)
            })
        }
      }
    })
  } catch (error) {
    console.error(error)
  }
}
const getStepData = async (faultId: string) => {
  try {
    const res = await queryFaultMessage({
      token: getToken() ?? '',
      faultId: faultId
    })
    if (res.statusCode === '0') {
      return res.data
    } else {
      return []
    }
  } catch (error) {
    console.error(error)
    return []
  }
}
const AddWorkOrderDialog = defineAsyncComponent(
  () => import('@/components/dialog/AddWorkOrder.vue')
)
const AddWorkOrderDialogRef = ref<InstanceType<typeof AddWorkOrderDialog> | null>(null)

const MessageLogDialog = defineAsyncComponent(
  () => import('@/components/basic/BasicStepDialog.vue')
)
const MessageLogDialogRef = ref<InstanceType<typeof MessageLogDialog> | null>(null)
const openMessage = (row: queryFaultTableCol) => {
  MessageLogDialogRef.value?.setData(row.faultId, '消息列表', getStepData)
  MessageLogDialogRef.value?.open()
}
const ignore = (row: queryFaultTableCol) => {
  try {
    ElMessageBox.alert('是否忽略该条故障上报，忽略后无法添加，需用户重新上报', '忽略故障上报', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: true,
      callback: async (action: Action) => {
        if (action === 'confirm') {
          IgnoreDialogRef.value?.setId(row.faultId, '忽略原因')
          IgnoreDialogRef.value?.open()
        }
      }
    })
  } catch (error) {
    console.error(error)
  }
}
const submitIgnore = async (faultId: string, remark: string) => {
  try {
    const res = await renewFaultStatus({
      token: getToken() ?? '',
      faultId: faultId,
      remark: remark,
      status: 4
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      IgnoreDialogRef.value?.close()
    } else {
      ElMessage.error(res.data)
    }
  } catch (error) {
    console.error(error)
  }
}
const addOrder = (row: queryFaultTableCol) => {
  AddWorkOrderDialogRef.value?.setData(row.faultId)
  AddWorkOrderDialogRef.value?.open()
}
const TextAreaDialog = defineAsyncComponent(
  () => import('@/components/basic/BasicTextAreaDialog.vue')
)
const IgnoreDialogRef = ref<InstanceType<typeof TextAreaDialog> | null>(null)
const AppMessageDialogRef = ref<InstanceType<typeof TextAreaDialog> | null>(null)
const push = (row: queryFaultTableCol) => {
  AppMessageDialogRef.value?.setId(row.phone, '推送消息')
  AppMessageDialogRef.value?.open()
}
const submitMessage = async (id: string, remark: string) => {
  try {
    const res = await SendMessage({
      token: getToken() ?? '',
      phone: id,
      content: remark,
      type: '通知'
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      AppMessageDialogRef.value?.close()
    } else {
      ElMessage.error(res.data)
    }
  } catch (error) {
    console.error(error)
  }
}
/** 拉入维修 */
const Maintenance = async (row: any) => {
  ElMessageBox.confirm('车辆拉入维修后，用户无法正常使用，是否拉入维修', '拉入维修', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await maintenanceShortTermBike({
        token: getToken() ?? '',
        bikeId: row.bikeId
      })
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        load()
      }
    } catch (error) {
      console.error(error)
      load()
    }
  })
}
</script>

<template>
  <div class="xy-container">
    <el-form :model="form" ref="formRef" inline>
      <el-form-item prop="phone" label="手机号">
        <el-input v-model="form.phone" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="workOrderId" label="工单编号">
        <el-input v-model="form.workOrderId" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="operator" label="处理人">
        <el-input v-model="form.operator" placeholder="请输入处理人姓名" />
      </el-form-item>
      <el-form-item prop="status" label="处理状态">
        <el-select v-model="form.status" placeholder="请输入" style="width: 120px">
          <el-option label="不限" value="" />
          <el-option label="未处理" value="0" />
          <el-option label="待处理" value="1" />
          <el-option label="处理中" value="2" />
          <el-option label="已忽略" value="4" />
          <el-option label="已处理" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleFormSearch">查询</el-button>
        <el-button @click="reset" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="data" v-loading="loading" class="no-border">
      <el-table-column prop="deviceCode" label="设备编号" align="center" min-width="100px" />
      <el-table-column
        prop="storeName"
        label="所属门店"
        align="center"
        min-width="120px"
        show-overflow-tooltip
      />
      <el-table-column prop="category" label="故障类型" align="center" min-width="100px" />
      <el-table-column
        prop="faultDescription"
        label="故障原因"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="图片" align="center" min-width="100px">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.imageUrls.split(',')[0]"
            :preview-src-list="scope.row.imageUrls.split(',')"
            :preview-teleported="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="上报时间"
        align="center"
        show-overflow-tooltip
        min-width="150"
      >
        <template #default="scope">
          <span>{{ dayjs(scope.row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="上报用户" align="center" min-width="120px" />
      <el-table-column
        prop="message"
        label="消息回复"
        align="center"
        show-overflow-tooltip
        min-width="100px"
      />
      <el-table-column prop="status" label="当前状态" align="center" min-width="100px">
        <template #default="scope">
          <span :style="formatStatusColor(scope.row.status)">{{
            formatStatus(scope.row.status)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="operationUser"
        label="处理人"
        align="center"
        min-width="130px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="operationTime"
        label="处理时间"
        align="center"
        min-width="150px"
        show-overflow-tooltip
      />
      <el-table-column prop="" label="处理备注" align="center" min-width="100px" />
      <el-table-column prop="workOrderId" label="工单编号" align="center" min-width="100px" />
      <el-table-column label="消息列表" align="center">
        <template #default="scope">
          <el-button link class="is-show" @click="openMessage(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="400px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            class="is-open"
            @click="ignore(scope.row)"
            v-if="scope.row.status === 0 && scope.row.status === 1"
            >忽略</el-button
          >
          <el-button
            v-if="scope.row.status !== 3 && scope.row.status !== 4"
            link
            type="primary"
            class="is-open"
            @click="handled(scope.row)"
            >处理完成</el-button
          >
          <el-button link type="primary" class="is-open" @click="push(scope.row)"
            >推送消息</el-button
          >
          <el-button
            link
            type="primary"
            class="is-open"
            @click="addOrder(scope.row)"
            v-if="!scope.row.workOrderId && scope.row.status === 0"
            >添加工单</el-button
          >
          <el-button
            link
            type="primary"
            class="is-open"
            @click="Maintenance(scope.row)"
            v-if="
              !scope.row.workOrderId &&
              scope.row.status === 0 &&
              isTimeBikeCode(scope.row.deviceCode)
            "
            >拉入维修</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div flex justify-end mt-20>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        background
        :total="pagination.total"
        layout="total,prev,pager,next,jumper,sizes"
      />
    </div>
    <add-work-order-dialog ref="AddWorkOrderDialogRef" @refresh="load" />
    <text-area-dialog ref="AppMessageDialogRef" @submit="submitMessage" />
    <text-area-dialog ref="IgnoreDialogRef" @submit="submitIgnore" />
    <message-log-dialog ref="MessageLogDialogRef" type="image" />
  </div>
</template>

<style scoped></style>
